package com.ssii.www.myproject.service.impl;

import com.ssii.www.myproject.common.util.LogUtils;
import com.ssii.www.myproject.common.util.PageList;
import com.ssii.www.myproject.domain.Permission;
import com.ssii.www.myproject.query.PermissionQuery;
import com.ssii.www.myproject.repository.PermissionRepository;
import com.ssii.www.myproject.service.PermissionService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class PermissionServiceImpl extends BaseServiceImpl<Permission, Long> implements PermissionService {
  @Autowired
  private PermissionRepository permissionRepository;

  private static final Logger logger = LogUtils.getLogger();

  @Override
  public Long change(Long state) {
    return state == -1L ? 1L : -1L;
  }

  @Override
  public List<Permission> getByUserId(Long id) {
    return permissionRepository.findPermissionsById(id);
  }


//  @Override
//  public Map<String, Object> findPermissionsByRoleId(Long row_id) {
//    Map<String, Object> map = new HashMap<>();
//    List<Permission> permissions = permissionRepository.findPermissionsByRoleId(row_id);
//    map.put("total", permissions.size());
//    map.put("page", (permissions.size() / 10) + 1);
//    map.put("rows", permissions);
//    return map;
//  }


  public PageList<Permission> getPagePermissionsByRoleId(PermissionQuery query) {

    List<Permission> permissions = permissionRepository.findPermissionsByRoleId(query.getRole_id());
    //角色没有权限时
    if(permissions.size()==1&&permissions.get(0)==null)return new PageList<>();
    PageList<Permission> pageList = new PageList<>();
    //得到当前role id下多少条数据
    int count = permissions.size();
    //1判断页数 封装为easyui的page
    int rows = query.getRows();
    int page = query.getPage();
    if ((count % rows) == 0) {
      pageList.setPage (count / rows);
    } else {
      pageList.setPage((count / rows) + 1);
    }
    //2封装为easyui的total
    pageList.setTotal(count);
    //分页方法得到分页数据
    int pageNumber = (page - 1) * rows;
    int pageSize = rows;
    List<Permission> permissionsByRoleId = null;
    try {
      permissionsByRoleId = permissionRepository.findPagePermissionsByRoleId(query.getRole_id(), pageNumber, pageSize);
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
    //3封装easyui的rows
    pageList.setRows(permissionsByRoleId);
    return pageList;
  }


}
